﻿using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;

public class XluaEngine : MonoBehaviour
{
    // **************************  xlua *************************
    internal static XLua.LuaEnv _xlua = new XLua.LuaEnv();
    public static string LuaSrcPath
    {
        get {
            return Application.dataPath + "/Lua";
        }
    }
    public static XLua.LuaEnv Lua
    {
        get {
            return _xlua;
        }
    }

    // **************************
    [SerializeField]
    private string mainFile = "main.lua";
    void Awake()
    {
        Lua.AddLoader(onEditorLoader);
        Lua.DoString(string.Format(" require '{0}'", mainFile));
        Debug.Log(mainFile + " :  " + LuaSrcPath);
    }
    
    byte[] onEditorLoader(ref string luaFile)
    {
        if(Directory.Exists(LuaSrcPath))
        {
            if(luaFile.EndsWith(".lua"))
                luaFile = luaFile.Substring(0,luaFile.LastIndexOf('.'));
            luaFile = luaFile.Replace('.', '/')+ ".lua";
            string absPath = Path.Combine(LuaSrcPath, luaFile);
            if (File.Exists(absPath))
                return File.ReadAllBytes(absPath);
        }
        return null;
    }

    internal static float lastGCTime = 0;
    internal const float GCInterval = 1;//1 second 
    private void Update()
    {
        if (Time.time - lastGCTime> GCInterval)
        {
            Lua.Tick();
            lastGCTime = Time.time;
        }
    }
}
